package com.zx.demo.demo.util;

import org.apache.commons.codec.binary.Base64;
import org.springframework.util.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AESUtil {

	public static String encrypt(String content, String key) throws Exception {
		if (StringUtils.isEmpty(content) || StringUtils.isEmpty(key))
			return null;
		if (key.length() != 16)
			return null;

		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
		byte[] bytes = cipher.doFinal(content.getBytes("utf-8"));
		return new String(new Base64().encode(bytes), "utf-8");
	}

	public static String decrypt(String content, String key) throws Exception {
		if (StringUtils.isEmpty(content) || StringUtils.isEmpty(key))
			return null;
		if (key.length() != 16)
			return null;

		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
		byte[] bytes = new Base64().decode(content);
		bytes = cipher.doFinal(bytes);
		return new String(bytes, "utf-8");
	}

	/**
	 * 龙城云消息推送加密
	 * 
	 * @param content
	 * @param key
	 * @return
	 */
	public static String encrypt(String content, String key, String iv) {
		try {
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
			IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes("UTF-8"));
			cipher.init(1, secretKeySpec, ivSpec);
			byte[] encrypted = cipher.doFinal(content.getBytes());
			return new String(Base64Wonder.encode(encrypted, 2), "UTF-8");
		} catch (Exception var6) {
			return "";
		}
	}

	/**
	 * 龙城云消息推送解密
	 * 
	 * @param content
	 * @param key
	 * @return
	 */
	public static String decrypt(String cipherText, String key, String iv) {
		try {
			byte[] cipherBytes = Base64Wonder.decode(cipherText, 2);
			SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
			IvParameterSpec ivSpec = new IvParameterSpec("E08ADE2699714B87".getBytes("UTF-8"));
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			cipher.init(2, secretKeySpec, ivSpec);
			byte[] decrypted = cipher.doFinal(cipherBytes);
			return new String(decrypted);
		} catch (Exception var7) {
			return "";
		}
	}

}
